import 'package:flutter/material.dart';
import 'package:extended_image/extended_image.dart';

class CommonImage extends StatelessWidget {
  final String src;
  final double? width;
  final double? height;
  final BoxFit? fit;
  final Widget? placeholder;
  final Widget? errorWidget;

  const CommonImage({
    Key? key,
    required this.src,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.placeholder,
    this.errorWidget,
  }) : super(key: key);

  /// 正则表达式判断是否为网络图片
  bool _isNetworkImage(String src) {
    final RegExp networkRegex = RegExp(
      r'^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)',
      caseSensitive: false,
    );
    return networkRegex.hasMatch(src);
  }

  /// 构建默认占位符
  Widget _buildDefaultPlaceholder() {
    return Container(
      width: width,
      height: height,
      color: Colors.grey[200],
      child: const Center(
        child: CircularProgressIndicator(
          strokeWidth: 2,
        ),
      ),
    );
  }

  /// 构建默认错误组件
  Widget _buildDefaultErrorWidget() {
    return Container(
      width: width,
      height: height,
      color: Colors.grey[300],
      child: const Center(
        child: Icon(
          Icons.error_outline,
          color: Colors.grey,
          size: 24,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 判断是否为网络图片
    if (_isNetworkImage(src)) {
      return ExtendedImage.network(
        src,
        width: width,
        height: height,
        fit: fit,
        cache: true, // 默认启用缓存
        cacheMaxAge: const Duration(days: 7), // 设置网络图片缓存时长为7天（磁盘缓存）
        clearMemoryCacheIfFailed: true,
        loadStateChanged: (ExtendedImageState state) {
          switch (state.extendedImageLoadState) {
            case LoadState.loading:
              return placeholder ?? _buildDefaultPlaceholder();
            case LoadState.completed:
              return state.completedWidget;
            case LoadState.failed:
              return errorWidget ?? _buildDefaultErrorWidget();
          }
        },
      );
    } else {
      // 处理本地资源图片 - 使用原生Image.asset确保尺寸稳定性
      return Image.asset(
        src,
        width: width,
        height: height,
        fit: fit ?? BoxFit.cover,
        // 错误处理
        errorBuilder: (context, error, stackTrace) {
          return errorWidget ?? _buildDefaultErrorWidget();
        },
      );
    }
  }
}